package top.xiaozhaobk.xiaofenshu.kv.biz.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.xiaozhaobk.framework.common.exception.BizException;
import top.xiaozhaobk.framework.common.response.Response;
import top.xiaozhaobk.xiaofenshu.kv.biz.domain.dataobject.NoteContentDO;
import top.xiaozhaobk.xiaofenshu.kv.biz.domain.repository.NoteContentRepository;
import top.xiaozhaobk.xiaofenshu.kv.biz.enums.ResponseCodeEnum;
import top.xiaozhaobk.xiaofenshu.kv.biz.service.NoteContentService;
import top.xiaozhaobk.xiaofenshu.kv.dto.req.AddNoteContentReqDTO;
import top.xiaozhaobk.xiaofenshu.kv.dto.req.DeleteNoteContentReqDTO;
import top.xiaozhaobk.xiaofenshu.kv.dto.req.FindNoteContentReqDTO;
import top.xiaozhaobk.xiaofenshu.kv.dto.rsp.FindNoteContentRspDTO;

import java.util.Optional;
import java.util.UUID;

@Service
@Slf4j
public class NoteContentServiceImpl implements NoteContentService {
    @Resource
    private NoteContentRepository noteContentRepository;

    @Override
    public Response<?> addNoteContent(AddNoteContentReqDTO addNoteContentReqDTO) {
        // 笔记 ID
        String noteId = addNoteContentReqDTO.getNoteId();
        // 笔记内容
        String content = addNoteContentReqDTO.getContent();

        // 构建数据库 DO 实体类
        NoteContentDO nodeContent = NoteContentDO.builder()
                .id(UUID.fromString(noteId)) // TODO: 暂时用 UUID, 目的是为了下一章讲解压测，不用动态传笔记 ID。后续改为笔记服务传过来的笔记 ID
                .content(content)
                .build();

        // 插入数据
        noteContentRepository.save(nodeContent);

        return Response.success();
    }

    /**
     * 查询笔记内容
     *
     * @param findNoteContentReqDTO
     * @return
     */
    @Override
    public Response<FindNoteContentRspDTO> findNoteContent(FindNoteContentReqDTO findNoteContentReqDTO) {
        String noteId = findNoteContentReqDTO.getNoteId();

        // 查询笔记内容
        Optional<NoteContentDO> optional = noteContentRepository.findById(UUID.fromString(noteId));

        // 判断是否存在
        if(optional.isEmpty()){
            throw new BizException(ResponseCodeEnum.NOTE_CONTENT_NOT_FOUND);
        }

        NoteContentDO noteContentDO = optional.get();
        // 构建返回数据
        FindNoteContentRspDTO findNoteContentRspDTO = FindNoteContentRspDTO.builder()
                .content(noteContentDO.getContent())
                .build();
        return Response.success(findNoteContentRspDTO);
    }

    @Override
    public Response<?> deleteNoteContent(DeleteNoteContentReqDTO deleteNoteContentReqDTO) {
        String noteId = deleteNoteContentReqDTO.getNoteId();
        // 删除笔记内容
        noteContentRepository.deleteById(UUID.fromString(noteId));
        return Response.success();
    }
}
